package com.jinlejia.feedback.question.ui;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.dialog.JLJCommonDialog;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.utils.DownloadUtil;
import com.jinlejia.erp.utils.IntenetUtil;
import com.jinlejia.erp.utils.MimeType;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.RecycleViewDivider;
import com.jinlejia.feedback.common.databinding.CommonEvent;
import com.jinlejia.feedback.databinding.FbActivityQuestionAllProgressBinding;
import com.jinlejia.feedback.question.adapter.AllProgressAdapter;
import com.jinlejia.feedback.question.http.QuestionAllProgressHelper;
import com.weight.CircleProgressBar;
import com.weight.CustomToast;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

/**
 * 全部跟进
 */
public class FbQuestionAllProgressActivity extends AppCompatActivity implements AllProgressAdapter.DownloadEvent, SwipeRefreshLayout.OnRefreshListener {
    private AllProgressAdapter adapter;
    private String taskCode; //任务编码 from Intent
    private QuestionAllProgressHelper helper;
    private FbActivityQuestionAllProgressBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.fb_activity_question_all_progress);
        helper = new QuestionAllProgressHelper(binding);
        Intent intent = getIntent();
        taskCode = intent.getStringExtra("taskCode");
        String taskTitle = intent.getStringExtra("taskTitle"); //任务名称 from Intent
        binding.progressTitleTextView.setText(String.valueOf(taskTitle));
        binding.setCommonEvent(CommonEvent.obtain());
        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.yfListRecyclerView.setHasFixedSize(true);
        binding.yfListRecyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, Color.parseColor("#13000000")));
        ArrayList<Map<String, Object>> data = new ArrayList<>();
        adapter = new AllProgressAdapter(data);
        binding.swipeRefreshLayout.setOnRefreshListener(this);
        binding.yfListRecyclerView.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);
        adapter.setDownloadEvent(this);
        getData();
    }

    private void getData() {
        helper.listTaskFollow(taskCode, new QuestionAllProgressHelper.ListTaskFollowCallBack() {
            @Override
            public void onResult(ArrayList<Map<String, Object>> result) {
                binding.swipeRefreshLayout.setRefreshing(false);
                adapter.setData(result);
                adapter.changeMode(YfListMode.MODE_DATA);
            }

            @Override
            public void onError() {
                adapter.changeMode(YfListMode.MODE_ERROR);
                binding.swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onEmpty() {
                adapter.changeMode(YfListMode.MODE_EMPTY);
                binding.swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    //region 文件下载 和 打开
    @Override
    public void onDownload(final CircleProgressBar progressBar, final String downloadUrl) {
        if (progressBar.getStatus() == CircleProgressBar.Status.LOADING) {
            //下载中，停止下载
            progressBar.setStatus(CircleProgressBar.Status.START);
            DownloadUtil.get().cancelTag(downloadUrl);
        } else if (progressBar.getStatus() == CircleProgressBar.Status.START) {
            //初始状态，开始下载
            if (IntenetUtil.getNetworkState(this) == IntenetUtil.NETWORN_WIFI) {
                //wifi环境直接下载
                downLoad(progressBar, downloadUrl);
            } else {
                //移动网络提示是否继续下载
                JLJCommonDialog dialog = new JLJCommonDialog(this, "提示", "当前为移动网络，是否继续?", "继续", "取消");
                dialog.show();
                dialog.setConfirmListener(new JLJCommonDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        downLoad(progressBar, downloadUrl);
                    }
                });
            }

        } else if (progressBar.getStatus() == CircleProgressBar.Status.END) {
            //已经下载，直接查看
            openFile(progressBar.getTag().toString());
        }
    }

    private void downLoad(final CircleProgressBar mProgressBar, final String downloadUrl) {
        mProgressBar.setStatus(CircleProgressBar.Status.LOADING);
        DownloadUtil.get().download(downloadUrl, "JLJFeedBack", downloadUrl, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(CircleProgressBar.Status.END);
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator).concat("JLJFeedBack")
                                        .concat(downloadUrl.substring(downloadUrl.lastIndexOf("/")));
                                mProgressBar.setTag(path);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloading(final int progress) {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(CircleProgressBar.Status.LOADING);
                                mProgressBar.setProgress(progress);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloadFailed() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(CircleProgressBar.Status.START);
                            }
                        })
                        .subscribe();
            }
        });
    }

    private void openFile(String path) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        File file = new File(path);
        if (file.exists()){
            //获取文件file的MIME类型
            String type = MimeType.getMIMEType(file);
            //设置intent的data和Type属性。
            intent.setDataAndType(Uri.fromFile(file), type);
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                CustomToast.showToast(this,"您没有可以打开该文件的应用",1500);
            }
        }else{
            CustomToast.showToast(this,"文件不存在",1500);
        }

    }


    @Override
    public void onRefresh() {
        getData();
    }
    //endregion
}
